package service

import (
	"choujiang/common/models"
	"choujiang/common/db"
	"math/rand"
	"time"
	"fmt"
	"choujiang/common/utils"
)

func GetAward() ([]model.Award, error) {
	award := make([]model.Award, 0)
	err := db.MysqlEngine.Where("status=1").Find(&award)
	for i := 0; i < len(award); i++ {
		award[i].Img = utils.AddPrefix(award[i].Img)
		award[i].Cover = utils.AddPrefix(award[i].Cover)
	}
	return award, err
}

func GetLottery(user *model.User) model.Award {
	awardList, _ := GetAward()
	award := getRand(awardList) //根据中将概率抽奖
	go acceptPrice(award, user) //携程保存领奖信息

	return award
}

func getRand(awardList []model.Award) model.Award {
	var proSum float64
	for i := 0; i < len(awardList); i++ {
		proSum += awardList[i].Chance
	}
	var award model.Award
	for i := 0; i < len(awardList); i++ {
		randNum := 1 + randNum(proSum)
		if randNum <= awardList[i].Chance {
			award = awardList[i]
			break
		} else {
			proSum -= awardList[i].Chance
		}
	}
	return award
}

func randNum(proSum float64) float64 {
	rand.Seed(time.Now().Unix())
	return float64(rand.Intn(int(proSum)))
}

//领取奖励
func acceptPrice(award model.Award, user *model.User) {
	costPoint := 200
	switch award.Type {
	case 1: //红包
		_, err := db.MysqlEngine.Exec("update user_extra set balance = balance + ?, point = point - ? where user_id = ?", award.Value, costPoint, user.Id)
		if err != nil {
			fmt.Printf("Add user balance err:", err)
		}
	case 2: //金币
		_, err := db.MysqlEngine.Exec("update user_extra set point = point + ? - ? where user_id = ?", award.Value, costPoint, user.Id)
		if err != nil {
			fmt.Printf("Add user point err:", err)
		}
	case 3: //实物
		_, err := db.MysqlEngine.Exec("update user_extra set point = point - ? where user_id = ?", costPoint, user.Id)
		if err != nil {
			fmt.Printf("Add user point err:", err)
		}
	case 4: //未中奖
		_, err := db.MysqlEngine.Exec("update user_extra set point = point - ? where user_id = ?", costPoint, user.Id)
		if err != nil {
			fmt.Printf("Add user point err:", err)
		}
	}
	//mgo记录抽奖信息
	db.Mgo.LogLottery(user.Id, award.Type, award.Value, award.Id)
}
